/*
 * jQuery Placeholder plugin
 *
 * This plugin is used to support the HTML5 placeholder attribute on most non-HTML5-compliant browsers.
 * 
 * Usage: put ".placeholder{color:#888}" into the css file and include this file.^.^
 * Author jiahui<lovise.lu@gmail.com>
 * Date 2012.5.26
 * Version: 1.1
 * Changelog 
 *  1.1 Add clean the placeholder when submit the form.
 *  1.0 support all kinds of input tag.
 */
$(function(){
	jQuery.support.placeholder = false;
	test = document.createElement('input');
	if('placeholder' in test) jQuery.support.placeholder = true;
	if(!jQuery.support.placeholder){
		//replace password fields with a fake field
		$(":password[placeholder]").each(function(){
			this.fakeField = $("<input type='text' class='"+$(this).attr("class")+"' id='"+$(this).attr("id")+"' tabindex='"+$(this).attr("tabindex")+"' />");
			this.fakeField.addClass('placeholder');
			this.fakeField.val($(this).attr('placeholder'));
			this.fakeField.bind('focus',{self:this},function(event) {
				$(this).hide();
				$(event.data.self).show();
				$(event.data.self).focus();
			}).keypress(function(event) {
				event.preventDefault();
			});
			this.fakeField.insertBefore($(this));
			this.fakeField.hide();
			$(this).blur(function(){
				var input = $(this);
				if (input.val() == "") {
					this.fakeField.show();
					$(this).hide();
				}
			}).blur();
		});
		//text fields
		$("[placeholder]").focus(function() {
			var input = $(this);
			if (input.val() == input.attr("placeholder")) {
				input.val("");
				input.removeClass('placeholder');
			}
		}).blur(function() {
			var input = $(this);
			if (input.val() == "" || input.val() == input.attr("placeholder")) {
				input.val(input.attr("placeholder"));
				input.addClass('placeholder');
			}
		}).blur();
		//chean the placeholder when submit the form
		$('form').each(function(){
			if($(this).find("[placeholder]").length > 0){
				$(this).submit(function(){
					$(this).find("[placeholder]").each(function(){
						if($(this).val() == $(this).attr('placeholder')){
							$(this).val('');
							$(this).removeClass('placeholder');
						}
					})
				});
			}
		})
	}
});
